('use strict');
/**
 * AES拦截
 * @authors 杨兴洲（of2502）
 * @date    2017/2/27 11:58
 * @version 1.0
 */
import CONFIG from '../config';
import { decodeCipher } from '../util/aes-util';

export default (req, res, next) => {
  let aesToken = req.headers.authorization || req.headers.Authorization;
  let adminId = req.query.adminId;
  if (!aesToken || !adminId) {
    return res.status(200).json({
      errcode: 99999,
      errmsg: '非法请求,禁止访问!'
    });
  }
  let data = decodeCipher(aesToken, CONFIG.EXTRACT_KEY);
  let [authAdminId, authTime] = data.split('&');
  if (!authAdminId || !data.startsWith(adminId) || !authTime) {
    return res.status(200).json({
      errcode: 99999,
      errmsg: 'token错误,禁止访问!'
    });
  }
  //校验token是否过期 （10分钟过期）
  if (new Date().getTime() - parseInt(authTime, 10) > 1000 * 60 * 10) {
    return res.status(200).json({
      errcode: 90000,
      errmsg: 'token过期,禁止访问!'
    });
  }
  next();
};
